package com.wza.interview.Clone;

import java.io.*;

/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author Administrator
 * @version [版本号, 2018/11/16]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class MyUtil
{
    private MyUtil() {
        throw new AssertionError();
    }

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(Person obj) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(obj);

        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bin);
        return (T) ois.readObject();

        // 说明：调用ByteArrayInputStream或ByteArrayOutputStream对象的close方法没有任何意义
        // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源，这一点不同于对外部资源（如文件流）的释放
    }

    public static int countWordInFile(String fileName, String word)
    {
        int counter = 0;

        FileReader in = null;
        BufferedReader bufferedReader = null;
        try
        {
            in = new FileReader(fileName);
            bufferedReader = new BufferedReader(in);

            String line = null;

            while ((line = bufferedReader.readLine()) != null)
            {
                int index = -1;

                while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0)
                {
                    counter++;
                    line = line.substring(index + word.length());
                }
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bufferedReader != null)
            {
                try
                {
                    bufferedReader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        return counter;
    }

    public void listFileName(String path)
    {
        File file = new File(path);

        for (File tmp : file.listFiles())
        {
            if (tmp.isFile())
            {
                System.out.println(tmp.getName());
            }
        }
    }
}
